package com.chacha.framework.dasboard.tools;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * @author rachmat_doni@smltech.co.id
 *
 */
public class DataJsonGrid {

	private List<String> properties;
	private List<Data> datas;
	private String nameRoot;
	
	public DataJsonGrid(List<String> properties){
		this.properties = properties;
		datas = new ArrayList<Data>();
	}
	
	public void setNameRoot(String nameRoot){
		this.nameRoot = nameRoot;
	}
	
	public void createData(String label, String value) {
		Data data = new Data();
		data.addData("\"" + label + "\": " + "\"" + value + "\" " + ",\n");
		datas.add(data);
	}
	
	public void addData(String label, String value) {
		Data data = datas.get(datas.size()-1);
		data.addData("\"" + label + "\": " + "\"" + value + "\" " + ",\n"); 
	}
	
	public void addObjectData(String label, Object value) {
		Data data = datas.get(datas.size()-1);
		data.addData("\"" + label + "\": " + value + ",\n"); 
	}
	
	public String getJSONData(){
		StringBuilder builder = new StringBuilder("{");
		StringBuilder builder1 = new StringBuilder(nameRoot + ": [ ");
		
		for(String prop: properties){
			builder.append( prop +", ");
		}
		
		for(Data dt: datas){
			builder1.append("{" + dt.getData()+ "},\n");
		}
		builder.append(StringUtils.removeEnd(builder1.toString(), ",\n") + " ]" + " }");
		
		return builder.toString();
	}
	
	private class Data{
		private List<String> dataString;
		
		public Data(){
			dataString = new ArrayList<String>();
		}
		
		public void addData(String data){
			dataString.add(data);
		}
		
		public String getData(){
			StringBuilder builder = new StringBuilder();
			
			for(String value : dataString){
				builder.append(value);
			}
			
			return StringUtils.removeEnd(builder.toString(), ",\n") + "\n";
		}
	}
}
